package com.ukao.cashregister.dialog;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.BagListAdapter;
import com.ukao.cashregister.adapter.OrderClothingAdapter;
import com.ukao.cashregister.base.BaseDialogFragment;
import com.ukao.cashregister.base.IAdapter;
import com.ukao.cashregister.base.IPage;
import com.ukao.cashregister.base.PageWrapper;
import com.ukao.cashregister.bean.BatchlTabBean;
import com.ukao.cashregister.bean.ClothIngManageBean;
import com.ukao.cashregister.bean.FactoryBatchBean;
import com.ukao.cashregister.bean.StringBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.retrofit.ApiCallback;
import com.ukao.cashregister.ui.sendFactory.BatchDetailsFragment;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.widget.StateButton;
import com.ukao.cashregister.widget.StateImageView;
import com.ukao.cashregister.widget.TwinklingLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Observable;



/**
 * 批次对话框
 */

public class IntoBagDialogFragment extends BaseDialogFragment {


    @BindView(R.id.close_btn)
    StateImageView closeBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.ordrer_num_tv)
    TextView ordrerNumTv;
    @BindView(R.id.cloth_recyclerView)
    RecyclerView clothRecyclerView;
    @BindView(R.id.clothing_refresh_layout)
    TwinklingLayout clothingRefreshLayout;
    @BindView(R.id.bag_recyclerView)
    RecyclerView bagRecyclerView;
    @BindView(R.id.bag_refresh_layout)
    TwinklingLayout bagRefreshLayout;
    @BindView(R.id.sure_pot_pocket_btn)
    StateButton surePotPocketBtn;
    @BindView(R.id.cancel)
    StateButton cancel;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.build_btn)
    StateButton buildBtn;
    private List<ClothIngManageBean.ListBean> mClotingData = new ArrayList<>();
    private List<BatchlTabBean.ListBean> mData = new ArrayList<>();


    private PageWrapper mPageWrapper;
    private Unbinder unbinder;


    private BagListAdapter mBagListAdapter;
    private OrderClothingAdapter mOrderClothingAdapter;
    private String orderId;

    private String ordrerNum;
    private boolean isAllCheck;

    public static IntoBagDialogFragment newInstance(String param1, String param2, boolean isAllCheck) {
        IntoBagDialogFragment fragment = new IntoBagDialogFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putBoolean(ARG_PARAM3, isAllCheck);

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        orderId = bundle.getString(ARG_PARAM1, "");
        ordrerNum = bundle.getString(ARG_PARAM2, "");
        isAllCheck = bundle.getBoolean(ARG_PARAM3, false);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_into_bag, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();


    }


    private void initView() {
        title.setText("入袋");
        bagRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        mBagListAdapter = new BagListAdapter(activity, mData);
        bagRecyclerView.setAdapter(mBagListAdapter);

        clothRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        mOrderClothingAdapter = new OrderClothingAdapter(activity, mClotingData);
        clothRecyclerView.setAdapter(mOrderClothingAdapter);
        IPage page = new IPage() {

            @Override
            public void load(int geIndex, int pageSize) {

                orderProductBatchIn(geIndex, pageSize);


            }
        };
        mPageWrapper = new PageWrapper<>(mIAdapter, page);
        page.setPageSize(13);
        bagRefreshLayout.startRefresh();
        clothingRefreshLayout.startRefresh();
        clothingRefreshLayout.setEnableLoadmore(false);
    }


    IAdapter mIAdapter = new IAdapter() {
        @Override
        public void setDataSource(List data, boolean isNextLoad) {


            mBagListAdapter.setDatas(data);
            bagRefreshLayout.finishRefreshing();
            bagRefreshLayout.setEnableLoadmore(isNextLoad);


        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {


            mBagListAdapter.addDatas(data);
            bagRefreshLayout.finishLoadmore();
            bagRefreshLayout.setEnableLoadmore(isNextLoad);

        }
    };

    @Override
    protected void initListener() {
        super.initListener();
        clothingRefreshLayout.setOnRefreshListener(mClothingRefreshListener);
        mOrderClothingAdapter.setOnItemClickListener(mOrderClothingListener);
        mBagListAdapter.setOnItemClickListener(mBagClickListener);
        bagRefreshLayout.setOnRefreshListener(mRefreshListenerAdapter);


    }

    private OnItemClickListener mOrderClothingListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {

            ClothIngManageBean.ListBean item = (ClothIngManageBean.ListBean) o;
            if (item.getInBatch()) return;
            item.setCheck(!item.isCheck());
            mOrderClothingAdapter.notifyDataSetChanged();


        }


    };
    private RefreshListenerAdapter mClothingRefreshListener = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            super.onRefresh(refreshLayout);
            clothingProList();

        }


    };
    private MyOnItemClickListener mBagClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {

            BatchlTabBean.ListBean item = (BatchlTabBean.ListBean) o;
            item.setCheck(!item.isCheck());

            if (item.isCheck()) {
                for (int j = 0; j < mData.size(); j++) {
                    if (i != j) {
                        mData.get(j).setCheck(false);
                    }
                }
                surePotPocketBtn.setVisibility(View.VISIBLE);
            }else{
                surePotPocketBtn.setVisibility(View.GONE);
            }
            mBagListAdapter.notifyDataSetChanged();

        }


    };

    private RefreshListenerAdapter mRefreshListenerAdapter = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            super.onRefresh(refreshLayout);

            mPageWrapper.loadPage(true);
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            super.onLoadMore(refreshLayout);

            mPageWrapper.loadPage(false);

        }
    };


    /**
     * 左边订单衣物列表
     */
    public void clothingProList() {
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("orderId", orderId);
        mHashMap.put("accessToken", SaveParamets.getToken(activity));
        addSubscription(apiStores().clothingProList(Constant.createParameter(mHashMap)),
                new ApiCallback<ClothIngManageBean>() {
                    @Override
                    public void onSuccess(ClothIngManageBean model) {

                        if (model.getHttpCode() == 200) {
                            List<ClothIngManageBean.ListBean> mData = model.getData().getList();
                            mOrderClothingAdapter.setDatas(mData);
                            int clothingCount = 0;
                            int accessoryCount = 0;
                            for (ClothIngManageBean.ListBean listBean : mData) {
                                if (!listBean.getInBatch() && isAllCheck) {
                                    listBean.setCheck(true);
                                }

                                if (listBean.getType() == 1) {  // 1.衣物 2.附件
                                    clothingCount = clothingCount + 1;
                                } else {
                                    accessoryCount = accessoryCount + 1;
                                }
                            }
                            int total = clothingCount + accessoryCount;
                            ordrerNumTv.setText("单号：" + ordrerNum + "     共" + total + "件(衣物" + clothingCount + "件，附件" + accessoryCount + "件)");

                        } else {
                            T.show(model.getMsg());

                        }
                    }


                    @Override
                    public void onFinish() {


                            try {
                                if (isAdded()&&clothingRefreshLayout!=null){ clothingRefreshLayout.onFinishRefresh();}
                            }catch (Exception e){

                            }

                    }
                });
    }

    /**
     * 送厂tab 列表
     */
    public void orderProductBatchIn(int pageNum, int pageSize) {
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("pageNum", pageNum + "");
        mHashMap.put("pageSize", pageSize + "");
        mHashMap.put("isFinish", "0");/*1是完成0未完成*/
        mHashMap.put("accessToken", SaveParamets.getToken(activity));
        addSubscription(apiStores().orderProductBatchIn(Constant.createParameter(mHashMap)),
                new ApiCallback<BatchlTabBean>() {
                    @Override
                    public void onSuccess(BatchlTabBean model) {

                        if (model.getHttpCode() == 200) {
                            List<BatchlTabBean.ListBean> mMoveData = model.getData().getList();
                            mPageWrapper.addDataSource(mMoveData, model.getData().getPages());

                        } else {
                            T.show(model.getMsg());

                        }
                    }


                    @Override
                    public void onFinish() {

                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.sure_pot_pocket_btn, R.id.close_btn,R.id.build_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case  R.id.build_btn:
                batchInadd("");
            break;

            case R.id.close_btn:
                dismiss();
                break;
            case R.id.sure_pot_pocket_btn:
                StringBuffer mStringBuffer1 = new StringBuffer();
                for (ClothIngManageBean.ListBean item : mClotingData) {
                    if (item.isCheck()) {
                        mStringBuffer1.append(item.getId()).append(",");

                    }

                }
                if (mStringBuffer1.length() == 0) {
                    T.show("请勾选衣物");
                    return;
                }

                String moveproductIds = mStringBuffer1.deleteCharAt(mStringBuffer1.length() - 1).toString();
                String moveId = "";
                for (int i = 0; i < mData.size(); i++) {

                    if (mData.get(i).isCheck())
                        moveId = mData.get(i).getId();
                }
                if (moveId.isEmpty()) {
                    T.show("请勾选要加入的袋号");
                    return;
                }

                BatchInReladd(moveId, moveproductIds);
                break;
        }
    }

    /**
     * 衣物 添加
     */
    public void BatchInReladd(String id, final String orderProIds) {
        surePotPocketBtn.setText("正在入袋...,");
        surePotPocketBtn.setEnabled(false);
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("inId", id);
        mHashMap.put("orderProIds", orderProIds);
        mHashMap.put("accessToken", SaveParamets.getToken(activity));
        Observable Observable;
        L.i("mHashMap=" + mHashMap.toString());
        Observable = apiStores().BatchInReladd(Constant.createParameter(mHashMap));
        addSubscription(Observable,
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {
                        if (model.getHttpCode() == 200) {

                            bagRefreshLayout.startRefresh();
                            clothingRefreshLayout.startRefresh();
                        } else {
                            T.show(model.getMsg());

                        }


                    }


                    @Override
                    public void onFinish() {
                        if (isAdded()){
                            surePotPocketBtn.setText("确定入袋");
                            surePotPocketBtn.setEnabled(true);
                        }

                    }

                });
    }

    public void batchInadd(String productIds) {

        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("orderProIds", productIds);
        mHashMap.put("accessToken", SaveParamets.getToken(activity));
        addSubscription(apiStores().batchInadd(Constant.createParameter(mHashMap)),
                new ApiCallback<FactoryBatchBean>() {
                    @Override
                    public void onSuccess(FactoryBatchBean model) {
                        if (model.getHttpCode() == 200) {


                    bagRefreshLayout.startRefresh();

                        } else {
                            T.show(model.getMsg());

                        }


                    }


                    @Override
                    public void onFinish() {

                    }

                });
    }

}
